package cn.moukou.dictator.util;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public class OssUtil {

    private static String endpoint = "oss-cn-shanghai.aliyuncs.com";
    private static String accessKeyId = "LTAI4G4brRGbdryVsSR7gtnX";
    private static String accessKeySecret = "awqCufc1g6FzdI5fNxJcELwz8q1e45";
    private static String bucketName = "tongji-dictator";

    public static void upload(String filepath, InputStream inputStream) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filepath, inputStream);

        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public static void delete(String filepath) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.deleteObject(bucketName, filepath);

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public static void download(String filename, String filepath, HttpServletResponse response) throws IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setContentType("application/force-download");// 设置强制下载不打开
        filename = URLEncoder.encode(filename,  "utf-8");
        response.addHeader("Content-Disposition",
                "attachment;fileName=" +  filename);// 设置文件名

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(bucketName, filepath);

        BufferedInputStream bis = new BufferedInputStream(ossObject.getObjectContent());
        OutputStream os = response.getOutputStream();

        byte[] buffer = new byte[1024];
        int i = bis.read(buffer);
        while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
        }
        ossClient.shutdown();
    }

    public static String getDownloadUrl(String filename, String filepath) throws UnsupportedEncodingException {
        filepath = filepath + "?response-content-disposition=attachment";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, filepath);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET);
        generatePresignedUrlRequest.setExpiration(expiration);
        String url = ossClient.generatePresignedUrl(generatePresignedUrlRequest).toString();
        int i =url.indexOf("?");
        String prefix = URLDecoder.decode(url.substring(0, i), "UTF-8");
        String suffix = url.substring(i+1);
        ossClient.shutdown();
        return prefix + "&" + suffix;
    }

    public static Map<String , String> getOSSConfig(String dir) {
        String host = "https://" + bucketName + "." + endpoint; // host的格式为 bucketname.endpoint
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            long expireTime = 300;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("OSSAccessKeyId", accessKeyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            return respMap;

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }
}
